<template>
  <div>
    <el-cascader ref="addressCascader" :key="cascaderKey" v-model="selectedOptions" style="width: 100%" filterable
      :clearable="clearable" :disabled="disabled" :options="options" :props="props" @change="change" :placeholder="placeholder"/>
  </div>
</template>

<script>
import { regionData, CodeToText, provinceAndCityData } from 'element-china-area-data'
export default {
  props: {
    value: '',
    props: {},
    disabled: {
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    isShowProvinceAndCity: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      selectedOptions: [],
      item: '',
      cascaderKey: 1,
      options: regionData
    }
  },
  watch: {
    options: {
      immediate: false,
      handler(val) {
        ++this.cascaderKey
        this.start()
      }
    },
    value: {
      immediate: true,
      handler(val) {
        this.start()
      }
    }
  },
  created() {
    if (this.isShowProvinceAndCity) {
      this.options = provinceAndCityData
    }
  },
  methods: {
    start() {
      if (!this.value) {
        this.selectedOptions = []
      } else if (this.value[2] == '666'){
        this.selectedOptions = [this.value[0], this.value[1]]
      } else {
        this.selectedOptions = this.value
      }
    },
    change(val) {
      this.$emit('input', val)

      // 香港，澳门只有两层
      var addressDetail = ''
      if ((val && val.length > 0) && (val[0] == 810000 || val[0] == 820000 )) {
        addressDetail = {
          provinceId: val[0].toString(),
          provinceName: CodeToText[val[0]],
          cityId: val[1].toString(),
          cityName: CodeToText[val[1]],
          districtId: '666',
          districtName: ''
        }
      } else {
        if (this.isShowProvinceAndCity) { // 只选择省市
          addressDetail = {
            provinceId: val[0].toString(),
            provinceName: CodeToText[val[0]],
            cityId: val[1].toString(),
            cityName: CodeToText[val[1]],
            districtId: '0',
            districtName: ''
          }
        } else {
          addressDetail = {
            provinceId: val[0].toString(),
            provinceName: CodeToText[val[0]],
            cityId: val[1].toString(),
            cityName: CodeToText[val[1]],
            districtId: val[2].toString(),
            districtName: CodeToText[val[2]]
          }
        }
      }

      this.$emit('selectAddressDetail', addressDetail)
    }
  }
}
</script>

<style>
</style>
